package com.sunny.fetch.service;

import com.sunny.common.pojo.SunResult;
import com.sunny.fetch.common.SysConfig;
import com.sunny.fetch.mapper.ApiMetaResultMapper;
import com.sunny.fetch.rest.BaseApi;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * @Author: sublun
 * @Date: 2021/3/25 14:23
 */
public abstract class BaseService <T extends BaseApi> {

    @Autowired
    private ApiMetaResultMapper metaResultMapper;

    private volatile T client;

    public void init() {
        // builder模式构建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SysConfig.get().getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 创建接口层的代理对象，内部通过动态代理创建了ApiService的代理对象
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        client = retrofit.create(tClass);
    }

    public T getClient() {
        if (client == null) {
            synchronized (this) {
                if (client == null) {
                    init();
                }
            }
        }
        return client;
    }



    public abstract SunResult execute();

    protected List<String> getFieldList(String apiCode) {
        return metaResultMapper.getResNameByCode(apiCode);
    }
}
